Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Java Operators

Ternary operator

About ternary operator

The ternary operator is a conditional operator that takes three operands and evaluates to one of two expressions depending on the value of the first operand. The ternary operator is also known as the conditional expression or the three-way operator. The syntax of the ternary operator is as follows:
condition ? expression1 : expression2
The first operand, condition, is evaluated. If the condition is true, the second operand, expression1, is evaluated and its value is returned. Otherwise, the third operand, expression2, is evaluated and its value is returned. Here is an example of how the ternary operator can be used to determine whether a number is even or odd:

Java - Ternary


int number = 10; // Determine if the number is even or odd String result = number % 2 == 0 ? "Even" : "Odd";
In this example, the first operand, number % 2 == 0, is evaluated. If the result of the expression is true, the second operand, "Even", is evaluated and its value, Even, is returned. Otherwise, the third operand, "Odd", is evaluated and its value, Odd, is returned. The ternary operator can be used to perform a variety of operations, such as: Determining whether a value is true or false Determining whether a number is even or odd Determining whether a string is empty or not Determining whether a file exists or not The ternary operator can be a concise way to write conditional statements, but it can also be difficult to read and understand. It is important to use the ternary operator judiciously and to make sure that it is clear what the code is doing. Another example

Ternary example


public class TernaryOperatorExample { public static void main(String[] args) { int marks = 85; String result = (marks >= 60) ? "Pass" : "Fail"; char grade = (marks >= 90) ? 'A' : (marks >= 80) ? 'B' : (marks >= 70) ? 'C' : 'D'; System.out.println("Result: " + result); System.out.println("Grade: " + grade); } }

Output

Result: Pass Grade: B
Here are some additional details about the ternary operator in Java: The ternary operator is evaluated from left to right. The first operand, condition, must be a Boolean expression. The second operand, expression1, and the third operand, expression2, can be of any type. The ternary operator can be used to replace if-else statements in some cases.

  📌TAGS

★ternary operator ★ operator ★ java ★ operator in java

Tutorials